<template>
  <el-form-item
    class="z-form-item"
    :class="{ 'z-value': isValue }"
    :style="{ width: width }"
    v-show="visible"
    :key="input.name"
    :prop="input.name"
    :rules="visible ? input.rules : null"
    v-on="$listeners"
  >
    <template v-if="input.formBuilder">
      <z-builder :name="input.formBuilder" :input="input" />
    </template>
    <z-filter-block
      v-else
      :input="input"
      :key="`${input.name}_block`"
      v-bind="$attrs"
      @focus="onFocus"
      @blur="onBlur"
      @keyup.enter="onEnter"
    />
    <span class="z-lable">{{ isRequired ? "* " + input.label : input.label }}</span>
  </el-form-item>
</template>

<script>
import ZFilterBlock from "../ZSearchFilter/ZFilterBlock";
import ZBuilder from "../ZBase/ZBuilder";
export default {
  name: "ZFormItem",
  components: {
    ZFilterBlock,
    ZBuilder,
  },
  props: {
    input: {
      type: Object,
      default: () => {},
    },
  },
  computed: {
    width({ input }) {
      return input.width ? input.width + "px" : "222" + "px";
    },
    visible() {
      return !this.input.hidden;
    },
    isValue({ input }) {
      if (input.multiple && input.value.length) {
        return true;
      }
      if (input.value || input.showKlabel || input.value === 0) {
        return true;
      }
      return false;
    },
    isRequired({ input }) {
      return !!input.rules?.find((item) => item.required);
    },
  },
  watch: {
    "input.value"(n, o) {
      if (n != o) {
        this.input.onChange?.(n);
      }
    },
  },
  methods: {
    onFocus(event) {
      this.input.onFocus?.(event);
    },
    onBlur(event) {
      this.input.onBlur?.(event);
    },
    onEnter(event) {
      this.input.onEnter?.(event);
    },
  },
};
</script>

<style lang="scss" scoped>
.z-form-item {
  margin-right: 16px;
  margin-bottom: 15px;

  .z-lable {
    position: absolute;
    top: 6px;
    left: 13px;
    z-index: 2;
    padding: 0 2px;
    font-size: 14px;
    color: #a8abb2;
    pointer-events: none;
    transition: all 0.2s;
  }

  &:focus-within .z-lable,
  &.z-value .z-lable {
    top: -15px;
    left: 9px;
    color: #409eff;
    background-color: #fff;
  }
}
</style>
